//
//  LRXLMeController.m
//  路人侠
//
//  Created by zhangxulong on 2/7/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXLMeController.h"
#import "LRXContentView.h"
#import "LRXHelpMesg.h"
#import "LRXAddrcInfoController.h"
#import "LRXThing.h"
#import "LRXMoreThingInfoCell.h"
#import "LRXMoreThingTableViewTitleView.h"
#import "LRXBuyThingController.h"
#import "MBProgressHUD+Extend.h"
#import "LRXPayViewController.h"
#import "LRXBedroom.h"
#import "LRXBuyThingCell.h"

@interface LRXLMeController() <
    ContentViewDelegate,
    UITableViewDataSource,
    UITableViewDelegate,
    UIGestureRecognizerDelegate,
    LRXAddrcInfoControllerDelegate,
    LRXMoreThingInfoCellDelegate,
    UIGestureRecognizerDelegate,
    BuyThingControllerDelegate,
    PayViewControllerDelegate

>

@property (nonatomic,strong) NSMutableArray * selectThings;
@property (nonatomic,weak) UIView * backView;
@property (nonatomic,weak) UIView * moreContenView;
@property (nonatomic,weak) LRXContentView * contentView;
@property (nonatomic,strong) NSIndexPath * delIndex;
@property (nonatomic,weak) UITableView * moreTable;
@end

static NSMutableArray * buy;
static NSMutableArray * saveTheChooseOfZero;

@implementation LRXLMeController
+(void)initialize{
    saveTheChooseOfZero = [NSMutableArray arrayWithCapacity:3];
    buy = [NSMutableArray arrayWithCapacity:3];
}
+(void)setBuy:(NSMutableArray *)buies{
    buy = buies;
}
+(NSMutableArray *)getBuy{
    return buy;
}


+(NSMutableArray *)getSaveThingOfZero{
    return saveTheChooseOfZero;
}
+(void)setSaveThingOfZero:(NSMutableArray *)saveThingArray{

    saveTheChooseOfZero = saveThingArray;

}
- (NSMutableArray *)selectThings
{
    if (_selectThings == nil) {
        _selectThings = [NSMutableArray array];
    }
    return _selectThings;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置界面背景色
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    //1、设置导航栏的Item
    [self layoutNaveView];
    
    //设置内容视图的内容
    [self layoutContentView];
    
    
}

// 设置 导航栏 的设置
- (void)layoutNaveView
{
    
    //1.1 设置标题
    self.navigationItem.title = @"我要求带";
    UIBarButtonItem * backBarItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(checkOrder)];
    self.navigationItem.backBarButtonItem = backBarItem;
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //颜色
    [rightBtn setTitleColor:[UIColor colorWithRed:253.0  green:253.0  blue:253.0 ] forState:UIControlStateNormal];
    
    
    //图片和文字的布局

    [rightBtn setImage:[UIImage imageNamed:@"checkIcon"] forState:UIControlStateNormal];
    //大小
    rightBtn.bounds = CGRectMake(0, 0, 30 * wScale, 36 * hScale);
    
    UIBarButtonItem * rightBtnItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
    self.navigationItem.rightBarButtonItem = rightBtnItem;
    [rightBtn addTarget:self action:@selector(checkOrder) forControlEvents:UIControlEventTouchUpInside];
}

//设置内容视图的内容
- (void)layoutContentView
{
    //建立三个UIView 并且设置位置
    LRXContentView * content = [[LRXContentView alloc]init];
    content.backgroundColor = [UIColor whiteColor];
    content.moreThingInfoDelegate = self;
    content.frame = CGRectMake(0, 0, MainScreenW, MainScreenH-statuesH-NavbarH);
    content.navH = NavbarH;
    self.contentView = content;
    [content layoutContentView];
   
    [self.view addSubview:content];
}

#pragma mark - LRXContentView 的代理方法 的实现  弹出详细的物品内容
- (void)clickMoreThingInfoBtn
{
    //背景 蒙板
    UIView * backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.54];
    backgroundView.frame = CGRectMake(0, -NavbarH, MainScreenW, MainScreenH);
    [self.view addSubview:backgroundView];
    self.backView = backgroundView;
    
    UITapGestureRecognizer * tip = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(popGrayBackGround)];
    [backgroundView addGestureRecognizer:tip];
    
    

    CGFloat moreInfoViewH = 500 * hScale;
    CGFloat moreInfoViewY = MainScreenH - moreInfoViewH - statuesH - NavbarH;
    
    
    //包含tableView的视图
    UIView * moreContentView = [[UIView alloc]init];
    moreContentView.frame = CGRectMake(0, 1006 * hScale, MainScreenW, moreInfoViewH);
    moreContentView.backgroundColor = [UIColor whiteColor];
    self.moreContenView = moreContentView;
    
//tableview 的设置
    
    CGFloat  moreInfoViewX = 50 * wScale;
    CGFloat moreInfoViewW = moreContentView.frame.size.width - 2 * moreInfoViewX;
    LRXMoreThingTableViewTitleView * titleView = [LRXMoreThingTableViewTitleView layoutTitleView];
    titleView.frame = CGRectMake(moreInfoViewX, 37 * hScale, moreInfoViewW, 65 * hScale);
    
    UITableView * moreInfoView = [[UITableView alloc]init];
    moreInfoView.frame = CGRectMake(moreInfoViewX, CGRectGetMaxY(titleView.frame), moreInfoViewW, moreInfoViewH - 190 * hScale);
    moreInfoView.delegate = self;
    moreInfoView.dataSource = self;
    moreInfoView.rowHeight = 90 * hScale;
    moreInfoView.showsVerticalScrollIndicator = NO;
    moreInfoView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.moreTable = moreInfoView;

    
    [moreContentView addSubview:titleView];
    [moreContentView addSubview:moreInfoView];
    [self.view addSubview:moreContentView];

    UIButton * addMoreBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [addMoreBtn setImage:[UIImage imageNamed:@"jiahao"] forState:UIControlStateNormal];
    addMoreBtn.frame = CGRectMake(0, 0, 50 * hScale, 50 * hScale);
    addMoreBtn.center = CGPointMake(moreContentView.center.x, moreContentView.frame.size.height - 50 * hScale);
   
    [addMoreBtn addTarget:self action:@selector(pushBuyThingViewController) forControlEvents:UIControlEventTouchUpInside];
    [moreContentView addSubview:addMoreBtn];
    
    [UIView animateWithDuration:0.7 animations:^{
        moreContentView.frame = CGRectMake(0, moreInfoViewY, MainScreenW, moreInfoViewH);
    }];
    
}
- (void)pushBuyThingView
{
    [self pushBuyThingViewController];
}
#pragma mark - 推出添加物品

- (void)pushBuyThingViewController
{
    LRXBuyThingController * thingController = [[LRXBuyThingController alloc]init];
    thingController.buyThingDelegate = self;
    
    
    thingController.buyThings = self.contentView.thingArray;
    [self.navigationController pushViewController:thingController animated:YES];
}


#pragma mark - 发布求带订单
- (void)checkOrder
{
    
    if ([self.contentView.sendAddrText isEqualToString:@"送达地址"]) {
        [MBProgressHUD showError:@"送达地址未填写" toView:self.view];
    }
    else if(self.contentView.thingArray.count <= 0)
    {
        [MBProgressHUD showError:@"您没有选择物品" toView:self.view];
    }
    else
    {
        LRXPayViewController * payController = [[LRXPayViewController alloc]init];
        payController.payDelegate = self;
        payController.buyThingArray = self.contentView.thingArray;
        payController.sendAddrText = self.contentView.sendAddrText;
        payController.bedroomStr = self.contentView.bedRoomStr;
        payController.bedRoomBlockStr = self.contentView.bedRoomBlockStr;
        payController.mesgViewText = self.contentView.mesgView.text;
        payController.startTimeFieldText = self.contentView.startTimeField.text;
        payController.endTimeFieldText = self.contentView.endTimeField.text;
        
        [self.navigationController pushViewController:payController animated:YES];
    }
    
}

#pragma mark - 弹回 详细物品内容
- (void)popGrayBackGround
{
    [self.backView removeFromSuperview];
    [UIView animateWithDuration:0.5 animations:^{
        self.moreContenView.frame = CGRectMake(23 * wScale, 1006 * hScale, 590 * wScale, self.view.frame.size.height - 197 * hScale);
    } completion:^(BOOL finished) {
        [self.moreContenView removeFromSuperview];
    }];
    
}


#pragma mark - ContentView的代理函数 跳转到 选择地址的界面 clickAddAddrcBtn
- (void)clickAddAddrcBtn:(LRXContentView *)contentView flag:(NSInteger)btnFlag
{
    LRXAddrcInfoController * addrInfo = [[LRXAddrcInfoController alloc]init];
    addrInfo.updateAddrTextDelegate = self;
    
    if (btnFlag == SENDADDRASSFLAG || btnFlag == SENDADDRBTNFLAG) {
        addrInfo.locationAddr = contentView.sendAddrText;
    }
    //用于标记 点击的是哪一个地址
    addrInfo.btnFlag = btnFlag;
    [self.navigationController pushViewController:addrInfo animated:YES];
    
}

#pragma mark - 更新 地址按钮的 代理方法  upAddrText
- (void)upAddrText:(NSString *)addrTexts btnFlag:(NSInteger)flag withBedRoom:(LRXBedroom *)bedRoom
{
    
    if (flag == SENDADDRBTNFLAG || flag == SENDADDRASSFLAG) {
        [self.contentView.sendAddrBtn setTitle:addrTexts forState:UIControlStateNormal];
        [self.contentView setSendAddr:addrTexts withBedroom:bedRoom];
    }
    
}

#pragma mark - tableView 的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * moreThingReused = @"moreThingReused";
    LRXMoreThingInfoCell * cell = [tableView dequeueReusableCellWithIdentifier:moreThingReused];
    if (cell == nil) {
        cell = [[LRXMoreThingInfoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:moreThingReused];
    }
    cell.cellUpateDelegate = self;
    [cell layoutMoreThing:self.selectThings[indexPath.row]];
    cell.cellIndexPath = indexPath;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.selectThings.count;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

/*改变删除按钮的title*/
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

/*删除用到的函数*/
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSLog(@"%s",__func__);
        [self.selectThings removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.contentView layoutThingView];
         
    }
}

#pragma mark - MoreThingCell的代理方法更新contentView 物品
- (void)updateCellInfo:(NSIndexPath *)cellIndexPath withCount:(NSInteger)count
{
    
    //通过调整moreView的数据来调整contentView 物品的数据
    for (int i = 0; i < self.contentView.thingArray.count; i++) {
        if (i == cellIndexPath.row) {
            LRXThing * thing = self.contentView.thingArray[i];
            thing.thingCount = [NSString stringWithFormat:@"%ld",count];
        }
    }
    
    if (count <= 0) {
        self.delIndex = cellIndexPath;
        //删除数量为0 的物品
        [self.selectThings removeObjectAtIndex:cellIndexPath.row];
        [self.moreTable deleteRowsAtIndexPaths:@[cellIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.moreTable reloadData];
    }
    
    [self.contentView layoutThingView];
}

#pragma mark - BuyThingControllerDelegate 的代理方法
- (void)popThingView:(NSArray *)buyThings
{
    self.contentView.thingArray = (NSMutableArray *)buyThings;
    self.selectThings = self.contentView.thingArray;
    [self.contentView layoutThingView];
    [self popGrayBackGround];
    
}

#pragma mark - payViewControllerDelegate
- (void)payForOrderResult:(NSString *)resultStatus
{
    if ([resultStatus isEqualToString:@"9000"]) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

#pragma mark - viewWillAppear
-(void)viewWillAppear:(BOOL)animated{
    
    if ([LRXBuyThingCell getBuyThing] == nil) {
        
        for (NSInteger index = 0; index < [LRXLMeController getSaveThingOfZero].count; index++) {
            LRXThing *thing = [LRXLMeController getSaveThingOfZero][index];
            [buy  addObject:thing];
        }
        [self popThingView:buy];
        
    }
    else{
        
        for (NSInteger index=0; index<[LRXLMeController getSaveThingOfZero].count; index++) {
            
            LRXThing *thing = [LRXLMeController getSaveThingOfZero][index];
            [[LRXBuyThingCell getBuyThing]  addObject:thing];
        }
        for (LRXThing *thing in [LRXBuyThingCell getBuyThing]) {
            if (thing.reChonoseAddCount != 0 ) {
                NSInteger re = [thing.thingCount integerValue];
                re -= thing.reChonoseAddCount;
                thing.thingCount = [NSString stringWithFormat:@"%ld",re];
                thing.reChonoseAddCount = 0;
            }
            if (thing.reChonoseSubCount != 0 ) {
                NSInteger re = [thing.thingCount integerValue];
                re += thing.reChonoseSubCount;
                thing.thingCount = [NSString stringWithFormat:@"%ld",re];
                thing.reChonoseSubCount = 0;
            }
        }
        [self popThingView:[LRXBuyThingCell getBuyThing]];
        
    }
}
@end
